<?php
/**
 * User: @lose
 * Date: 2019-10-23
 * Time: 16:59
 */

namespace Frieza\Modules\Devidepackage\Controllers;

use App\Admin\Extensions\Tools\ReleasePost;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\theParagraph\Room as mRoom;
use Doraemon\amqp\CommunityQueue;
use Doraemon\model\ImageTagging\PredictImages;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Biz\service\admin\PhotoTag;
use Doraemon\service\AdminTag\Schedule;
use Doraemon\service\Photos;
use Doraemon\model\AdmPicTags;
use Encore\Admin\Widgets\Form;
use Doraemon\model\admTag;
use Doraemon\model\Photos as dbPhoto;
use Doraemon\cache\Queue;
use Encore\Admin\Layout\Row;
use Doraemon\service\Tag;
use Doraemon\model\Pics;
use Doraemon\model\WordEmbedding\KeywordScoreSearchRelation;
use Doraemon\model\DevidePackage\UserPackage;
use Doraemon\model\DevidePackage\PackageRelatedInfo;
use Doraemon\model\WordEmbedding\KeywordObjectRelationVtwo;
use Doraemon\model\NewTag\Tag as dbTag;


class OperatePackageController extends Controller
{
    const PAGE_SIZE = 20;

    const TAG_MOULDS = '/home/adm_rsync_dir/tags_moulds.txt';
    const CENTER_FILE = '/home/adm_rsync_dir/center_tags.json';
    const ATTR_FILE = '/home/adm_rsync_dir/attr_tags.json';
    const CENTER_FILE_2_0 = '/home/adm_rsync_dir/center_tags_2_0.json';
    const ATTR_FILE_2_0 = '/home/adm_rsync_dir/attr_tags_2_0.json';

    public function continuePackage(Request $request, Content $content, $package_id)
    {
        $params = $request->all();
        //判断当前用户是否有此任务包权限
        $package_info = UserPackage::getPackageClaimant($package_id);
        $package_manager = Admin::user()->isRole('package_manager');
        if(!$package_manager) {
            if((Admin::user()->id != $package_info['claimant']) || !in_array($package_info['check_status'], UserPackage::OPERATE_STATUS)) {
                return $content
                    ->withError('您无权访问此页面', '请确认此任务包已被你认领且处于可操作状态');
            }
        }

        //获取任务包中内容信息
        $note_id = '';
        if(isset($params['id']) && $params['id']) {
            $note_id = $params['id'];
        }
        $only_empty = false;
        if(isset($params['only_empty']) && $params['only_empty']) {
            $only_empty = true;
        }
        $package_detail = PackageRelatedInfo::getPackageRelations($package_id, $note_id, $only_empty);

        $note_ids = array_unique(array_column($package_detail, 'note_id'));
        $pic_ids_really = array_unique(array_column($package_detail, 'pic_id'));
        $pic_num = count($pic_ids_really);
        $rows = $note_ids ?? [];
        $total = count($note_ids) ?? 0;
        $ids = empty($rows) ? [] : $rows;
        //本页
        $per_page = $params['per_page'] ? : 20;
        if($params['page']) {
            $ids = array_slice($ids, ((int)$params['page'] - 1) * $per_page, $per_page);
        } else {
            $ids = array_slice($ids, 0, $per_page);
        }
        $photos = Photos::getPhotos($ids); // 通过id获取图片信息

        //获取单图标签
        $picTags = AdmPicTags::getRelInfosByIds($ids);

        $pic_ids = array_column($photos, 'pic_list');
        $pic_ids_new = [];
        if($pic_ids && is_array($pic_ids)) {
            foreach($pic_ids as $pic_json) {
                if(isset($pic_json) && $pic_json) {
                    $pic_ids_new[] = implode(',', array_column(json_decode($pic_json, true), 'pic_id'));
                }
            }
        }
        $pic_ids_new_str = implode(',', $pic_ids_new);
        $pic_ids_new_arr = explode(',', $pic_ids_new_str);

        $pic_ids = empty($photos) ? [] : $pic_ids_new_arr;

        //算法图片标签
        $tagMap = empty($pic_ids) ? [] : PredictImages::getRobotLabel($pic_ids);
        //算法文本标签
        $tagMapWord = empty($pic_ids) ? [] : KeywordObjectRelationVtwo::getByObjIds($ids);
        $tagMapWord = $this->formatTags($tagMapWord);
        //标签模板
        $moulds = [];
        if(file_exists(self::TAG_MOULDS)) {
            $moulds = json_decode(file_get_contents(self::TAG_MOULDS), true);
        }
        //审核备注信息
        $adm_remarks = [];
        if($package_detail && is_array($package_detail)) {
            foreach($package_detail as $pic_info) {
                if(!empty($pic_info['adm_remark'])) {
                    $adm_remarks[$pic_info['note_id']][$pic_info['pic_id']] = $pic_info['adm_remark'];
                }
            }
        }

        $i = 1;
        foreach ($photos as &$info) {
            if(!isset($info['id'])) {
                continue;
            }
            $info['photo_id'] = $info['id'];
            $info['id'] = $i;
            $info['pic_list'] = json_decode($info['pic_list'], true);
            $info['package_id'] = $package_info['package_id'];
            $info['package_status'] = $package_info['check_status'];
            $info['is_checker'] = $package_manager;
            if(isset($adm_remarks[$info['photo_id']]) && is_array($adm_remarks[$info['photo_id']]) && $adm_remarks[$info['photo_id']]) {
                $info['adm_remark'] = json_encode($adm_remarks[$info['photo_id']], JSON_UNESCAPED_UNICODE);
            } else {
                $info['adm_remark'] = '';
            }
            if($info['pic_list'] && is_array($info['pic_list'])) {
                foreach($info['pic_list'] as $k=>$pic_id) {
                    $pic_id_real = $pic_id['pic_id'];
                    //过滤掉任务包中不包含的pic
                    if(in_array($pic_id_real, $pic_ids_really)) {
                        $tags = json_decode($picTags[$pic_id_real]['tags_json'], true);
                        if($tags && is_array($tags)) {
                            foreach($tags as $key=>$tag_info) {
                                if(empty($tag_info['name'])) {
                                    unset($tags[$key]);
                                }
                            }
                        }
                        $info['pic_tag_list'][$k]['photo_id'] = $info['photo_id'];
                        $info['pic_tag_list'][$k]['pic_id'] = $pic_id_real;
                        $info['pic_tag_list'][$k]['img_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $pic_id_real, ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                        $info['pic_tag_list'][$k]['pic_status'] = $tempTag['pic_status'] ?? '';
                        //算法预测标签
                        $info['pic_tag_list'][$k]['algorithm_tags'] = (array) $tagMap[$pic_id_real];

                        if(isset($tagMapWord[$info['photo_id']]) && is_array($tagMapWord[$info['photo_id']])) {
                            $centers = (string) $tagMap[$pic_id_real]['centers'].','. (string) $tagMapWord[$info['photo_id']]['centers'];
                            $centers = implode(',', array_filter(explode(',', $centers)));
                            $info['pic_tag_list'][$k]['algorithm_tags'] = ['centers' => $centers, 'attrs' => ''];
                        } else {
                            if(empty($tagMap[$pic_id_real])) {
                                $tagMap[$pic_id_real] = ['centers' => '', 'attrs' => ''];
                            }
                            $info['pic_tag_list'][$k]['algorithm_tags'] = (array) $tagMap[$pic_id_real];
                            $info['pic_tag_list'][$k]['algorithm_tags']['attrs'] = '';
                        }

                        //pic已有标签
                        $info['pic_tag_list'][$k]['pic_tags'] = (array) array_values((array)$tags);
                        //模板标签
                        $info['pic_tag_list'][$k]['mould_tags'] = $moulds;
                        $info['expand'] = $this->_getPicExpand(array_values($info['pic_tag_list']), $pic_id_real.rand(1,1000));
                        $info['expand'] .= $this->_getDivLine();
                    }
                }
            }
            $i++;
        }
        $options = [
            'perPage' => $per_page,
        ];

        $gridModel = new pGridDataModel($photos, $total, $options);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {

            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();

            $grid->filter(function (Grid\Filter $filter) {

                $filter->equal('only_empty', '仅看未打标签内容')->checkbox([
                    1   => '仅看未打标签内容'
                ]);

            });

            $grid->column('photo_id', 'ID')->display(function() {
                return "<a href='http://manage.haohaozhu.me/Admin/Photos/detail/photo_id/$this->photo_id' target='_blank' >".$this->photo_id."</a>";
            })->width(100);
            $grid->column('uid', '用户信息')->userBasicInfo();
            $grid->column('addtime', '发图时间')->display(function() {
                return date('Y-m-d H:i:s', $this->addtime);
            })->width(150);
            $grid->column('remark', '图说');
            $grid->column('adm_remark', '审核备注问题信息')->display(function() {
                if($this->package_status != UserPackage::STATUS_UNSUBMIT && $this->is_checker) {
                    return $this->adm_remark.'<br><a class="fa reload-data fa-check-warning adm_remark" href="javascript:;" data-package-id="'.$this->package_id.'" data-note-id="'.$this->photo_id.'" >备注信息</a><br>';
                }
                if($this->package_status != UserPackage::STATUS_UNSUBMIT && !$this->is_checker) {
                    return $this->adm_remark;
                }
            });

            $grid->column('information', '标签信息')->expand(function($model) {
                $pic_tags = $model->pic_tag_list;
                if($pic_tags && is_array($pic_tags)) {
                    return $this->expand;
                } else {
                    return '';
                }
            }, true);
        });

        Admin::Script($this->adm_remark_popup());
        Admin::Script($this->jsPhoto());
        return $content
            ->header('分包图片打标签(任务包id:『'.$package_id.'』)')
            ->breadcrumb(
                ['text' => 'pic打标签分包管理', 'url' => '/devidepackage/index/1'],
                ['text' => '打标签列表', 'url' => '/devidepackage/index/continuepackage/'.$package_id]
            )
            ->body($listGrid);
    }

    public function jsPhoto()
    {
        return <<<SCRIPT
        $.cachedScript = function( url, options ) {
            options = $.extend( options || {}, {
                dataType: "script",
                cache: true,
                url: url
            });
          return jQuery.ajax( options );
        };
        $.when(
               $.cachedScript('/vendor/js/frieza-fe/antd-3.26.12.min.js'),
            ).done(function(){
                 $.when(
                    $.cachedScript('/vendor/js/frieza-fe/picTag.js'),
                    $.Deferred(function(deferred){
                        $(deferred.resolve);
                })
                ).done(function(){
                    $(document).trigger('js.loaded-finished')
                });
            });
SCRIPT;
    }

    private function _getPicExpand($picArr, $pic_id)
    {
        if ($picArr) {
            $picData = json_encode($picArr,JSON_UNESCAPED_UNICODE);
            return "<div id='$pic_id'></div>
           
            <script>
                function init_{$pic_id}(){
                    var picData = $picData;
                    const container = document.getElementById('$pic_id');
                    console.log(picData); 
                    console.log(container);
                    ReactDOM.render(React.createElement(picTag.default,{picData:picData}), container);
                }
                $(document).one('js.loaded-finished',function(){
                     init_{$pic_id}()
                });
            </script>
            ";
        }
        return '';
    }

    /**
     * 分割线
     * @return string
     */
    private function _getDivLine()
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }

    public function tagSearch(Request $request)
    {
        $rs = [];
        $match = [];
        $search = $request->get('q');
        $type = $request->get('type');

        if($type == 1) {
            //中心词
            if(file_exists(self::CENTER_FILE_2_0)) {
                $center_pinyin_arr = json_decode(file_get_contents(self::CENTER_FILE_2_0), true);
            } else {
                $center_arr = admTag::getCenterTags();
                $center_pinyin_arr = Tag::getPinyin($center_arr);
            }
            foreach($center_pinyin_arr as $index=>$tag) {
                if(stripos($index, $search, 0) === 0) {
                    $rs[$index]['id'] = $index;
                    $rs[$index]['text'] = $tag;
                }
            }
        } else if($type == 2){
            //属性
            if(file_exists(self::ATTR_FILE_2_0)) {
                $attr_pinyin_arr = json_decode(file_get_contents(self::ATTR_FILE_2_0), true);
            } else {
                $attr_arr = admTag::getAttrTags();
                $attr_pinyin_arr = Tag::getPinyin($attr_arr);
            }
            foreach ($attr_pinyin_arr as $index => $tag) {
                if (stripos($index, $search, 0) === 0) {
                    $rs[$index]['id'] = $index;
                    $rs[$index]['text'] = $tag;
                }
            }
        }
        if($rs && is_array($rs)) {
            if(isset($rs[$search])) {
                $match = $rs[$search];
                unset($rs[$search]);
                $rs = array_values(array_merge([$match], array_values($rs)));
            }
        }

        $result = [
            'total' => count($rs),
            'per_page' => count($rs),
            'current_page' => 1,
            'last_page' => 1,
            'next_page_url' => null,
            'prev_page_url' => null,
            'from' => 1,
            'to' => count($rs),
            'data' => array_values($rs)
        ];

        return json_encode($result);

    }

    //打标签提交
    public function submitTags(Request $request)
    {
        $request = $request->all();
        $center_pinyin_arr = [];
        $attr_pinyin_arr = [];
        //参数
        $note_id = $request['note_id'];
        $pic_id = $request['pic_id'];
        $tags_json = $request['tags_json'];
        $recommend_tags = $request['recommend_tags'];
        if(file_exists(self::CENTER_FILE_2_0)) {
            $center_pinyin_arr = (array) json_decode(file_get_contents(self::CENTER_FILE_2_0), true);
        }
        if(file_exists(self::ATTR_FILE_2_0)) {
            $attr_pinyin_arr = (array) json_decode(file_get_contents(self::ATTR_FILE_2_0), true);
        }
        $filter_tags = [];
        //后端数据校验
        $tags_arr = json_decode($tags_json, true);
        if($tags_arr && is_array($tags_arr)) {
            foreach($tags_arr as $k=>&$tag_info) {
                $attrs_arr_check = [];
                if(isset($tag_info['name']) && !in_array($tag_info['name'], $center_pinyin_arr)) {
                    $filter_tags[] = $tag_info['name'];
                    unset($tags_arr[$k]);
                    continue;
                }

                if(isset($tag_info['attrs']) && trim($tag_info['attrs'])) {
                    $attrs_arr = explode(',', $tag_info['attrs']);
                    if($attrs_arr && is_array($attrs_arr)) {
                        foreach($attrs_arr as $index=>$attr) {
                            if(in_array($attr, $attr_pinyin_arr)) {
                                $attrs_arr_check[] = $attr;
                            } else {
                                $filter_tags[] = $attr;
                            }
                        }
                        $tag_info['attrs'] = implode(',', array_unique($attrs_arr_check));
                    }
                }

            }
        }

        $note_tags = AdmPicTags::getRelInfosByIds([$note_id]);

        //$data['tags_json'] = $tags_json;
        $data['tags_json'] = json_encode(array_values($tags_arr), JSON_UNESCAPED_UNICODE);
        $data['admin_id'] = Admin::user()->id;
        $tags_old_arr = [];
        if($note_tags[$pic_id] && is_array($note_tags[$pic_id])) {
            //旧tags_json
            $tags_arr_old = json_decode($note_tags[$pic_id]['tags_json'], true);
            $tags_old = '';
            if($tags_arr_old && is_array($tags_arr_old)) {
                foreach($tags_arr_old as $tag_info) {
                    $tags_old.=$tag_info['name'].','.$tag_info['attrs'].',';
                }
                $tags_old_arr = array_filter(array_unique(explode(',', $tags_old)));
            }

            $data['edittime'] = time();
            AdmPicTags::edit($pic_id, $data);
        } else {
            $data['note_id'] = $note_id;
            $data['pic_id'] = $pic_id;
            $data['addtime'] = time();
            AdmPicTags::add($data);
        }

        //更新photo表
        $photo_info = dbPhoto::getPhoto($note_id);
        $admin_tag_old = [];
        if($photo_info && is_array($photo_info)) {
            $admin_tag_old = array_filter(explode(',', $photo_info['admin_tag']));
        }
        $tags_arr = json_decode($tags_json, true);
        $admin_tag_new = '';
        if($tags_arr && is_array($tags_arr)) {
            foreach($tags_arr as $tag_info) {
                $admin_tag_new.=$tag_info['name'].','.$tag_info['attrs'].',';
            }
            $admin_tag_new = array_filter(array_unique(explode(',', $admin_tag_new)));

            //取差集
            $diff = array_values(array_diff($tags_old_arr, $admin_tag_new));
            $admin_tag_new = array_filter(array_unique(array_merge($admin_tag_old, $admin_tag_new)));
            foreach($admin_tag_new as $k=>$tag) {
                foreach($diff as $diff_tag) {
                    if(trim($tag) == trim($diff_tag)) {
                        unset($admin_tag_new[$k]);
                    }
                }

            }
            $admin_tag_new = implode(',', $admin_tag_new);
            $photo_data['admin_tag'] = (string) $admin_tag_new;
            $photo_data['edittime'] = time();
            $photo_data['status'] = dbPhoto::STATUS_SUCCESS;
            dbPhoto::updatePhotoById($note_id, $photo_data);
        } else {
            if($tags_old_arr && is_array($tags_old_arr) && $admin_tag_old && is_array($admin_tag_old)) {
                $diff = array_values(array_diff($tags_old_arr, []));
                foreach($admin_tag_old as $k=>$tag) {
                    foreach($diff as $diff_tag) {
                        if(trim($tag) == trim($diff_tag)) {
                            unset($admin_tag_old[$k]);
                        }
                    }
                }
                $admin_tag_new = implode(',', $admin_tag_old);
                $photo_data['admin_tag'] = (string) $admin_tag_new;
                $photo_data['edittime'] = time();
                $photo_data['status'] = dbPhoto::STATUS_SUCCESS;
                dbPhoto::updatePhotoById($note_id, $photo_data);
            }
        }

        //更新算法标签表
        $predicts = PredictImages::getRobotLabelForCheck($pic_id);
        if($predicts && is_array($predicts)) {
            foreach($predicts as $predict) {
                if(in_array($predict['predict_label'], explode(',', $recommend_tags))) {
                    PredictImages::updateCheck($predict['id'], $predict['predict_label']);
                }
            }
        }
        // 添加到队列，更新搜索图片
        CommunityQueue::insertQueue('queue/photo/editphoto', [
            'photo_id' => $note_id
        ], CommunityQueue::QUEUE_COMMUNITY);
        $rs = [
            'code' => 1,
            'data' => 'success',
            'tags_json' => $data['tags_json']
        ];

        return json_encode($rs, JSON_UNESCAPED_UNICODE);
    }

    //算法文本标签格式化
    public function formatTags($tag_infos)
    {
        $rs = [];
        if($tag_infos && is_array($tag_infos)) {
            $all_tags = dbTag::getAllByWhere([
                "tag_status" => dbTag::TAG_STATUS_ON
            ]);
            $center_arr = array_column($this->getTree($all_tags, dbTag::TAG_COMMUNITY), 'tag');
            $attr_arr = dbTag::getAttrTags();
            $center_arr = array_diff($center_arr, $attr_arr);
            foreach($tag_infos as $tag_info) {
                if(in_array($tag_info['keyword'], $center_arr)) {
                    $rs[$tag_info['obj_id']]['centers'][] = $tag_info['keyword'];
                }
            }
            if($rs && is_array($rs)) {
                foreach($rs as $k=>$tags) {
                    $rs[$k]['centers'] = implode(',', (array) $tags['centers']);
                    $rs[$k]['attrs'] = '';
                }
            }
        }
        return $rs;
    }

    //递归排序树
    public function getTree($tags, $pid, $level = 1)
    {
        static $list = [];
        if($tags && is_array($tags)) {
            $value['tag_levels'] = '';
            foreach ($tags as $key => $value) {
                if ($value['parent_id'] == $pid) {
                    $value['deep'] = $level;
                    //把数组放到list中
                    $list[] = $value;
                    unset($tags[$key]);
                    $this->getTree($tags, $value['id'], $level + 1);
                }
            }
        }

        return $list;
    }

    //备注弹窗
    public function adm_remark_popup()
    {
        return <<<SCRIPT
           
            $('.adm_remark').unbind('click').click(function() {
                var note_id = $(this).data('note-id');
                var package_id = $(this).data('package-id');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '备注问题pic',
                    shadeClose: true,
                    shade: false,
                    maxmin: false,
                    area: ['893px', '600px'],
                    content: package_id+'/'+note_id
                });
		    });
SCRIPT;
    }

    public function admRemarkPop(Request $request, Content $content, $package_id, $note_id)
    {
        $request = $request->all();

        $noteRelatedInfo = PackageRelatedInfo::getPackageRelations($package_id, $note_id);
        $gridModel = new pGridDataModel($noteRelatedInfo, count($noteRelatedInfo), []);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disablePagination();
            $grid->disableActions();

            $grid->column('id');
            $grid->column('package_id', '任务包id');
            $grid->column('pic_id', '图片id');
            $grid->column('adm_remark', '问题pic备注')->editable();
        });

        return $content
            ->header('pic打标签问题图片备注')
            ->body($listGrid->render());
    }

    public function editPicRemark(Request $request, $package_id, $note_id, $id)
    {
        $request = $request->all();
        $data['adm_remark'] = $request['value'];
        if(empty($data['adm_remark'])) {
            $data['has_problem'] = 0;
        } else {
            $data['has_problem'] = 1;
        }
        $data['edittime'] = date('Y-m-d H:i:s', time());
        $rs = PackageRelatedInfo::updatePackageBaseInfo($id, $data);
        if($rs) {
            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        }
        return response()->json([
            'status' => false,
            'message' => "修改失败",
        ]);
    }

}